/*
 * Copyright (c) 2010-2019. Axon Framework
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.axonframework.axonserver.connector.command;

import org.axonframework.common.Registration;

/**
 * Wrapper around standard Axon Framework {@link Registration}. Notifies messaging server when registration is
 * cancelled or closed, and delegates the close/cancel to the normal registration.
 *
 * @author Marc Gathier
 * @since 4.0
 */
public class AxonServerRegistration implements Registration {

    private final Registration wrappedRegistration;
    private final Runnable closeCallback;

    /**
     * Instantiate an {@link AxonServerRegistration}, which wraps the given {@code wrappedRegistration} and runs the
     * provided {@code closeCallback} on a {@link #close()} and {@link #cancel()} call
     *
     * @param wrappedRegistration the {@link Registration} wrapped by this Axon Server specific registration
     * @param closeCallback       a {@link Runnable} executed on a {@link #close()} and {@link #cancel()} call
     */
    public AxonServerRegistration(Registration wrappedRegistration, Runnable closeCallback) {
        this.wrappedRegistration = wrappedRegistration;
        this.closeCallback = closeCallback;
    }

    @Override
    public boolean cancel() {
        boolean result = wrappedRegistration.cancel();
        if (result) {
            closeCallback.run();
        }
        return result;
    }
}
